//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ia\fn_unloadConvoy.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_vehicle","_units","_drivers","_vehicles","_groups"];
DEFAULT_PARAM(_vehicle,0,objNull);

_units = [];
_drivers = [];
_vehicles = [];
_groups = [];
if (!(isNull _vehicle)) then {
	if (IS_OBJECT(_vehicle)) then {
		if (_vehicle isKindOf "AllVehicles" && {count(crew _vehicle) > 2}) then {
			_drivers set [count _drivers, driver _vehicle];
			_vehicles set [count _vehicles, _vehicle];
			{
				if (alive _x && {(driver _vehicle) != _x} && {(gunner _vehicle) != _x} && {_x in assignedCargo _vehicle}) then {
					_units set [count _units, _x];
					if !(group _x  in _groups) then {
						_groups set [count _groups, group _x];
					};
				};
			} foreach (crew _vehicle);
		};
	} else {
		if (IS_GROUP(_vehicle)) then {
			{
				if (vehicle _x != _x) then {
					if !((vehicle _x) in _vehicles) then {
						_vehicles set [count _vehicles, vehicle _x];
						if !(isNull (driver(vehicle _x))) then {
							_drivers set [count _drivers, driver(vehicle _x)];
						};
					};
					if (alive _x && {(driver (vehicle _x)) != _x} && {(gunner (vehicle _x)) != _x} && {_x in assignedCargo (vehicle _x)}) then {
						_units set [count _units, _x];
						if !(group _x  in _groups) then {
							_groups set [count _groups, group _x];
						};
					};
				};
			} foreach (units _vehicle);
		};	
	};
};
if (count _units > 0) then {
	[_vehicles,_drivers,_units,_groups] spawn {
		TRACE_1("Start Unload",_this);
		private ["_vehicles","_drivers","_units","_groups","_vehicle"];
		DEFAULT_PARAM(_vehicles,0,[]);
		DEFAULT_PARAM(_drivers,1,[]);
		DEFAULT_PARAM(_units,2,[]);
		DEFAULT_PARAM(_groups,3,[]);
		{
			doStop _x;
		} foreach _drivers;
		sleep 1;
		waitUntil { ({!( alive _x) || (speed _x <= 1)} count _vehicles) > 0 };
		waitUntil {
			{
				_vehicle = _x;
				if (speed _vehicle <= 1 && (count crew _vehicle) > 2) then {
					{
						if (_x in _units) then {
							TRACE_1("Leave Vehicle",ARR_2(_vehicle,_x,assignedVehicleRole _x));
							_x leaveVehicle _vehicle;
							if (_x == leader _x) then {
								[_x, getPos _x, 300] call FFUNC(patrol);
								(group _x) setCombatMode "RED";
								(group _x) setBehaviour "COMBAT";
								(group _x) setSpeedMode "FULL";
							};
						};
					} foreach (crew _vehicle);
				};
			} foreach _vehicles;
			({!( alive _x) || (speed _x <= 1)} count _vehicles) >= (count _vehicles)
		};
		{
			_x enableAI "FSM";
			_x enableAI "TARGET";
			_x enableAI "AUTOTARGET";
		} foreach _drivers;
		TRACE_1("End Unload",_vehicles);
	};
};

TRACE("End");
TMFPROFILERSTOP;